﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CRM.Database.Model
{
    public class TrainingsSchedulesCollection : AbstractCollection
    {
        /// <summary>
        /// Стaтическая коллекция 
        /// </summary>
        protected static List<TrainingsSchedules> _list;

        /// <summary>
        /// Список объектов
        /// </summary>
        public List<TrainingsSchedules> TrainingsSchedulesList
        {
            get
            {
                return Entities.TrainingsSchedules.OrderByDescending(p => p.PlannedDate).ToList();
                if (_list == null)
                    _list = DB.Entities.TrainingsSchedules.ToList();
                return _list;
            }
        }

        /// <summary>
        /// Возвращает расписание выездных курсов и вебинаров
        /// </summary>
        public List<TrainingsSchedules> OutsideSchedulesTable
        {
            get
            {
                var result = new List<TrainingsSchedules>();
                foreach (TrainingsSchedules schedule in TrainingsSchedulesList)
                {
                    if (schedule.PlannedDate > DateTime.Now)
                    {
                        if (schedule.IdTrainingCoursesStatus > 2 && schedule.IdTrainingCoursesStatus < 6)
                        {
                            if (schedule.TrainingsCourses != null)
                            {
                                if (schedule.IdTrainingCoursesType == 1 || schedule.IdTrainingCoursesType == 3)
                                {
                                    result.Add(schedule);
                                }
                            }
                        }
                    }
                }
                return result;
            }
        }

        /// <summary>
        /// Обнуление статической коллекции
        /// </summary>
        protected override void SetStaticListToNULL()
        {
            _list = null;
        }

        /// <summary>
        /// Получение статического списка для хранения объектов
        /// </summary>
        /// <returns></returns>
        public override object GetStaticCollection()
        {
            return _list;
        }

        /// <summary>
        /// Получение элемента из коллекции по идентификатору
        /// </summary>
        /// <param name="itemId">Идентификатор</param>
        /// <returns>Элемент</returns>
        public override object GetItemById(int itemId)
        {
            return Entities.TrainingsSchedules.Find(itemId);
        }

        /// <summary>
        /// Возвращает список расписаний, c активными курсами заданного типа 
        /// </summary>
        /// <param name="courseType"></param>
        /// <param name="actualDate">Актуальная дата (начиная с сегодняшнего дня)</param>
        /// <returns></returns>
        public List<TrainingsSchedules> GetSchedulesListByCourseType(int courseType, bool actualDate = false)
        {
            var schedulesList = new List<TrainingsSchedules>();

            if (actualDate)
            {
                foreach (TrainingsSchedules item in TrainingsSchedulesList)
                {
                    if (item.PlannedDate >= DateTime.Now)
                    {
                        if (item.TrainingsCourses != null)
                            if (item.IdTrainingCoursesType == courseType)
                                if (item.IdTrainingCoursesStatus == 3)
                                    schedulesList.Add(item);
                    }
                }
            }
            else
            {
                foreach (TrainingsSchedules item in TrainingsSchedulesList)
                {
                    if (item.TrainingsCourses != null)
                        if (item.IdTrainingCoursesType == courseType)
                            if (item.IdTrainingCoursesStatus == 3)
                                schedulesList.Add(item);
                }
            }

            return schedulesList;
        }

        /// <summary>
        /// Возвращает список расписаний, c активными курсами заданного типа 
        /// </summary>
        /// <param name="courseType"></param>
        /// <returns></returns>
        public List<TrainingsSchedules> GetSchedulesByCourseType(int courseType)
        {
            var schedulesList = new List<TrainingsSchedules>();
            foreach (TrainingsSchedules item in TrainingsSchedulesList)
            {
                if (item.TrainingsCourses != null)
                    if (item.IdTrainingCoursesType == courseType)
                        if (item.IdTrainingCoursesStatus == 3)
                            schedulesList.Add(item);
            }
            return schedulesList;
        }

        #region Overrides of AbstractCollection

        /// <summary>
        /// Обновление элемента в коллекции
        /// </summary>
        /// <param name="item">Новый элемент</param>
        /// <param name="userLogin">Логин пользователя, который делает изменения</param>
        /// <returns>Результат операции</returns>
        public bool Update(object item, string userLogin)
        {
            var newObject = (TrainingsSchedules) item;
            if (newObject == null)
                return false;

            var object4Update = GetItemByIdFromDatabase(newObject.GetKeyValue()) as TrainingsSchedules;
            if (object4Update == null)
                return false;

            object4Update.IdTrainingsCource = newObject.IdTrainingsCource;
            object4Update.PlannedDate = newObject.PlannedDate;
            object4Update.IdProfineRegion = newObject.IdProfineRegion;
            object4Update.IdTrainingsPlace = newObject.IdTrainingsPlace;
            object4Update.IdTrainingsTrainer = newObject.IdTrainingsTrainer;
            object4Update.CourseCost = newObject.CourseCost;
            object4Update.ParticipantCost = newObject.ParticipantCost;
            object4Update.CountAvailable = newObject.CountAvailable;
            object4Update.CountRequested = newObject.CountRequested;
            object4Update.CountApproved = newObject.CountApproved;
            object4Update.CountActual = newObject.CountActual;
            object4Update.IdTrainingCoursesStatus = newObject.IdTrainingCoursesStatus;
            object4Update.IdTrainingCoursesType = newObject.IdTrainingCoursesType;
            object4Update.IdTrainingsCity = newObject.IdTrainingsCity;
            
            if(newObject.IdTrainingsAuditorium != null)
                object4Update.IdTrainingsAuditorium = newObject.IdTrainingsAuditorium;


            return base.Update(object4Update, userLogin);
        }

        /// <summary>
        /// Получение списка элементов
        /// </summary>
        /// <returns>Список элементов</returns>
        public override List<object> GetList()
        {
            return new List<object>(TrainingsSchedulesList);
        }

        /// <summary>
        /// Получение типа текущего элемента
        /// </summary>
        /// <returns></returns>
        protected override Type GetItemType()
        {
            return typeof (TrainingsSchedules);
        }

        #endregion
    }
}